# coding:utf-8
'''
Created on 2011-3-10
使用SGMLParser库来解析HTML
@author: Administrator
'''

from sgmllib import SGMLParser
import htmlentitydefs

class BaseHTMLProcessor(SGMLParser):
    # 通用工具，可以通过扫描标记和文本来处理HTML文件。
    def reset(self):
        self.pieces = []
        SGMLParser.reset(self)
        
    def unknow_starttag(self, tag, attrs):
        # 解析每个开始标签都会使用到。
        # attrs是一个包含多(attr, value)元组的集合如：<pre class="screen">那么 tag="pre"，
        # attrs=[("class", "screen")]]
        strattrs = "".join([' %s="%s"' % (key, value) for key, value in attrs])
        self.pieces.append("<%(tag)s%(strattrs)s>" % locals())
        
    def unknow_endtag(self, tag):
        self.pieces.append("</%(tag)s>" % locals())
        
    def handle_charref(self, ref):
        self.pieces.append("&#%(ref)s" % locals())
        
    def handle_entityref(self, ref):
        self.pieces.append("&%(ref)s" % locals())
        if htmlentitydefs.entitydefs.has_key(ref):
            self.pieces.append(";")
            
    def handle_data(self, text):
        self.pieces.append(text)
        
    def handle_comment(self, text):
        self.pieces.append("<!--%(text)s-->" % locals())
        
    def handle_pi(self, text):
        self.pieces.append("<?%(text)s>" % locals())
        
    def handle_decl(self, text):
        self.pieces.append("<!%(text)s>" % locals())
        
    def output(self):
        return "".join(self.pieces)